#ifndef _SERVER_H_
#include "server.h"
#endif

#include <iostream>
#include <cassert>
#include <string>

//////////////////////////////////////////////////////////////////////////


Server::Server()
:m_Conn(true)
{
    AddEventToObserve(Observer::NETWORK_ACCEPTED_NEW_CONNECTION);
    AddEventToObserve(Observer::NETWORK_SEND_COMPLETE_TCP);
    AddEventToObserve(Observer::NETWORK_SEND_COMPLETE_UDP);
    AddEventToObserve(Observer::NETWORK_RECEIVE_COMPLETE_TCP);
    AddEventToObserve(Observer::NETWORK_RECEIVE_COMPLETE_UDP);

    m_Conn.AddObserver(this);
}


//////////////////////////////////////////////////////////////////////////


void Server::Accept()
{
    m_Conn.Accept();
}


//////////////////////////////////////////////////////////////////////////


void Server::SendResponseTCP()
{
    std::string strTCP("TCP: I have received your message\n");
    Packet bufferTCP( strTCP.c_str(), strTCP.length() );
    m_Conn.SendTCP(bufferTCP);
}


//////////////////////////////////////////////////////////////////////////


void Server::SendResponseUDP()
{
    std::string strUDP("UDP: I have received your message\n");
    Packet bufferUDP( strUDP.c_str(), strUDP.length() );
    m_Conn.SendUDP(bufferUDP);
}


//////////////////////////////////////////////////////////////////////////


void Server::OnEvent( Event _event, Observable* _observable )
{
    switch (_event)
    {
    case Observer::NETWORK_ACCEPTED_NEW_CONNECTION:
        {
            std::cout << "Server accepted new connection" << std::endl;
            break;
        }
        
    case Observer::NETWORK_SEND_COMPLETE_TCP:
        {
            std::cout << "TCP: Server sent response to client" << std::endl;
            break;
        }
        
    case Observer::NETWORK_SEND_COMPLETE_UDP:
        {
            std::cout << "UDP: Server sent response to client" << std::endl;
            break;
        }
        
    case Observer::NETWORK_RECEIVE_COMPLETE_TCP:
        {
            Packet buffer = m_Conn.GetRecvDataTCP();
            std::string str( buffer.Data(), buffer.Size() );
            std::cout << "TCP: Server received message from client: " << str << std::endl;

            SendResponseTCP();

            break;
        }

    case Observer::NETWORK_RECEIVE_COMPLETE_UDP:
        {
            Packet buffer = m_Conn.GetRecvDataUDP();
            std::string str( buffer.Data(), buffer.Size() );
            std::cout << "UDP: Server received message from client: " << str << std::endl;

            SendResponseUDP();

            break;
        }

    default:
        assert(0);
        break;
    }
}


//////////////////////////////////////////////////////////////////////////
